package qinggui.mlz.console.controller.export;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import qinggui.mlz.console.domain.category.CategoryExportVO;
import qinggui.mlz.console.domain.category.CategoryVO;
import qinggui.mlz.module.category.entity.Category;
import qinggui.mlz.module.category.service.CategoryService;
import qinggui.mlz.module.utils.BaseUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class ExportCategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 原生Poi导出类目表
     * @param response HTTP响应对象，用于设置下载文件的响应头和输出流
     * @throws UnsupportedEncodingException 当文件名编码不支持时抛出此异常
     */
//    @RequestMapping("/export/categoryList")
//    public void exportCategoryList(HttpServletResponse response) throws UnsupportedEncodingException {
//        // 1. 获取数据
//        List<Category> allCategory = categoryService.getAllCategory();
//        // 2. 创建文件对象
// //        Workbook workbook = new HSSFWorkbook();// xls格式
//        Workbook workbook = new XSSFWorkbook();// xlsx格式
//        // 3. 创建工作簿sheet
//        Sheet sheet = workbook.createSheet("分类列表");
//        // 4. 创建单元格样式, 设置单元格背景色和字体加粗
//        CellStyle cellStyle = workbook.createCellStyle();
//        Font font = workbook.createFont();
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
//        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        font.setBold(true);
//        cellStyle.setFont(font);
//        // 5. 创建列
//        String[] headers = {"父类目", "类目名称", "类目图片", "创建时间", "更新时间"};
//        Row row1 = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            Cell cell = row1.createCell(i);
//            cell.setCellValue(headers[i]);
//            cell.setCellStyle(cellStyle);
//        }
//        // 6. 将数据写进入
//        for (int i = 0; i < allCategory.size(); i++) {
//            Category category = allCategory.get(i);
//            Row row2 = sheet.createRow(i + 1);
//            if (category.getParentId() == null) {
//                row2.createCell(0).setCellValue("");// 空串
//            } else {
//                row2.createCell(0).setCellValue(category.getParentId());
//            }
//            row2.createCell(1).setCellValue(BaseUtils.str(category.getCategoryName()));
//            row2.createCell(2).setCellValue(BaseUtils.str(category.getCategoryImage()));
//            row2.createCell(3).setCellValue(BaseUtils.str(BaseUtils.timeStamp2Date(category.getCreateTime())));
//            row2.createCell(4).setCellValue(BaseUtils.str(BaseUtils.timeStamp2Date(category.getUpdateTime())));
//        }
//        // 7. 自动列宽
//        for (int i = 0; i < headers.length; i++) {
//            sheet.autoSizeColumn(i);
//            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 12 / 10);
//        }
//        // 8. 响应头
//        String fileName = URLEncoder.encode("类目表_" + LocalDate.now() + ".xlsx", "UTF-8");
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//    }

    /**
     * easyExcel导出类目表
     * @param response HTTP响应对象，用于设置下载文件的响应头和输出流
     * @throws IOException 当IO操作异常
     */
    @RequestMapping("/easyExcelExport/categoryList")
    public void easyExcelExportCategoryList(HttpServletResponse response) throws IOException {
        // 1. 查数据
        List<Category> list = categoryService.getAllCategory();
        // 2. 转 VO
        List<CategoryExportVO> voList = list.stream().map(c -> {
            CategoryExportVO vo = new CategoryExportVO();
            vo.setParentId(c.getParentId());
            vo.setCategoryName(c.getCategoryName());
            vo.setCategoryImage(c.getCategoryImage());
            vo.setCreateTime(c.getCreateTime());
            vo.setUpdateTime(c.getUpdateTime());
            return vo;
        }).collect(Collectors.toList());

        // 3. 设置响应头
        String fileName = URLEncoder.encode("类目表_" + LocalDate.now() + ".xlsx", "UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        // 4. 一行写出
        EasyExcel.write(response.getOutputStream(), CategoryExportVO.class)
                .sheet("分类列表")
                .doWrite(voList);
    }
}
